package com.ruoyi.system.annotation;

import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.vo.UserData;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class ClaimsAspect {

    @Pointcut("execution(* com.ruoyi.system.controller..*(..))") // 匹配所有 controller 包及其子包中的方法
    public void controllerMethods() {}

    @Before("controllerMethods()")
    public void beforeControllerMethod(JoinPoint joinPoint) {
        String token = SecurityUtils.getToken();

        if (token != null && !token.isEmpty()) {

            UserData userData = getUserDataFromRedis(token);

                // 设置到上下文中
           UserContext.setUserData(userData);

        }
    }



    private UserData getUserDataFromRedis(String token) {

        Claims claims = JwtUtils.parseToken(token);


        // 创建 UserData 对象
        UserData userData = new UserData();

        // 设置 UserData 对象的字段，如果对应的值存在
        if (claims.get("store_id") != null) {
            userData.setStoreId(Integer.parseInt(claims.get("store_id").toString()));
        }
        if (claims.get("database_name") != null) {
            userData.setDatabaseName(claims.get("database_name").toString());
        }
        if (claims.get("user_id") != null) {
            userData.setUserId(Integer.parseInt(claims.get("user_id").toString()));
        }
        if (claims.get("user_key") != null) {
            userData.setUserKey(claims.get("user_key").toString());
        }
        if (claims.get("merchant_id") != null) {
            userData.setMerchantId(Integer.parseInt(claims.get("merchant_id").toString()));
        }
        if (claims.get("table_name") != null) {
            userData.setTableName(claims.get("table_name").toString());
        }
        if (claims.get("username") != null) {
            userData.setUsername(claims.get("username").toString());
        }


        try {

            // 切换数据库



        } catch (ClassCastException e) {
            // 处理类型转换异常
            // 可以记录日志或抛出自定义异常
            e.printStackTrace();
        }

        return userData;
    }



}
